package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MessagesService messagesService;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;

    //查询今日佳人数据
    public TodayBest todayBest() {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //调用API查询
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //没有匹配的佳人,设置一个默认值
        if (recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        //佳人详情信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        //将RecommendUser与UserInfo转化为TodayBest对象
        TodayBest tb = TodayBest.init(userInfo,recommendUser);
        //返回
        return tb;
    }

    //查询分页推荐好友列表
    public PageResult recommendation(RecommendUserDto dto) {
        //获取用户id
        Long toUserId = UserHolder.getUserId();
        //调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(),dto.getPagesize(),toUserId);
        //获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //判断列表是否为空
        if (items == null || items.size() == 0){
            return pr;
        }
        //提取所有推荐的用户id(佳人id)列表
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        //构建查询条件(筛选)，批量查询所有符合条件的用户(佳人)详细信息{"id":UserInfo}
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        Map<Long,UserInfo> map = userInfoApi.findByIds(ids,userInfo);
        //循环推荐的数据列表
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info != null){
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        //构造返回值
        pr.setItems(list);
        return pr;
    }

    //查看佳人详情
    public TodayBest personalInfo(Long userId) {
        //根据用户id查询，用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //根据操作人id和查看的用户id，查询两者的推荐数据
        RecommendUser recommendUser = recommendUserApi.queryByUserId(userId,UserHolder.getUserId());
        //构造返回值
        return TodayBest.init(userInfo,recommendUser);
    }

    //查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java吗?":question.getTxt();
    }

    //回复陌生人问题
    public void replyQuestions(Long userId, String reply) {
        //构造消息数据
        Long currentUserId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(currentUserId);
        Map map = new HashMap();
        map.put("userId",currentUserId);
        map.put("huanXinId", Constants.HX_USER_PREFIX+currentUserId);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",strangerQuestions(userId));
        map.put("reply",reply);
        String message = JSON.toJSONString(map);
        //调用HuanXinTemplate对象，发送消息
        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, message);
        //发送失败抛异常
        if (!aBoolean){
            throw new BusinessException(ErrorResult.error());
        }
    }

    //探花推荐用户列表
    public List<TodayBest> queryCardsList() {
        //查询推荐列表,排除喜欢不喜欢
        List<RecommendUser> users = recommendUserApi.queryCardsList(UserHolder.getUserId(),10);
        //判断数据是否存在,不存在构造默认数据
        if (CollUtil.isEmpty(users)){
            users = new ArrayList<>();
            String[] userIds = recommendUser.split(",");
            for (String userId : userIds) {
                RecommendUser ru = new RecommendUser();
                ru.setUserId(Convert.toLong(userId));
                ru.setToUserId(UserHolder.getUserId());
                ru.setScore(RandomUtil.randomDouble(60,90));
                users.add(ru);
            }
        }
        //构造VO
        List<Long> userIds = CollUtil.getFieldValues(users, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds,null);
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            UserInfo userInfo = infoMap.get(user.getUserId());
            if (userInfo != null){
                TodayBest vo = TodayBest.init(userInfo, user);
                vos.add(vo);
            }
        }
        return vos;
    }

    //探花-喜欢
    public void likeUser(Long likeUserId) {
        //调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserId(),likeUserId,true);
        if (!save){
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        //操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        //判断是否双向喜欢,是添加好友
        Boolean aBoolean = redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + likeUserId, UserHolder.getUserId().toString());
        if (aBoolean){
            //添加好友
            messagesService.contacts(UserHolder.getUserId());
        }
    }
    //探花-不喜欢
    public void notLikeUser(Long likeUserId) {
        //调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserId(), likeUserId, false);
        if (!save){
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        //操作redis，删除喜欢的数据,写入不喜欢的数据(喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),likeUserId.toString());
        //判断是否双向喜欢，删除好友
    }

    //附近的人
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //调用API查询附近的用户（返回的是附近的人的所有用户id，包含当前用户的id）
        List<Long> userIds = userLikeApi.queryNearUser(UserHolder.getUserId(),Double.valueOf(distance));
        //判断集合是否为空
        if (CollUtil.isEmpty(userIds)){
            return new ArrayList<>();
        }
        //调用UserInfoApi根据用户id查询用户详情
        UserInfo ui = new UserInfo();
        ui.setGender(gender);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds,ui);
        //构造返回值vo
        List<NearUserVo> vos = new ArrayList<>();
        for (Long userId : userIds) {
            if (userId == UserHolder.getUserId()){
                continue;
            }
            UserInfo userInfo = infoMap.get(userId);
            if (userInfo != null){
                NearUserVo vo = NearUserVo.init(userInfo);
                vos.add(vo);
            }
        }
        return vos;
    }
}
